#!/bin/bash
## <info> Reset OpenXPKI certificates and database
test $(whoami) != "root" && echo "Please run this as root: sudo $0" && exit 1
set -o pipefail

#
# Exit handler
#
LOG=$(mktemp)
function _exit () {
    if [ $1 -ne 0 -a $1 -ne 333 ]; then
        echo -e "\nERROR ($0) Last command exited with code $1, output:" && cat $LOG
    fi
    rm -f $LOG
    exit $1
}
trap '_exit $?' EXIT

#
# Recreate certificates and DB
#
echo -e "Recreating database and certificates"

echo -e "- stopping OpenXPKI"
openxpkictl stop                                                  >$LOG 2>&1

set -e

echo -e "- re-creating database and tables"
/code-repo/tools/testenv/mysql-create-db.sh                       >$LOG 2>&1
/code-repo/tools/testenv/mysql-create-schema.sh                   >$LOG 2>&1

echo -e "- creating and importing sample certificates"
rm -rf /etc/openxpki/ca/
$OXI_TEST_SAMPLECONFIG_DIR/contrib/sampleconfig.sh                >$LOG 2>&1
chown -R openxpki:root /etc/openxpki/ca/
chmod -R 750 /etc/openxpki/ca/

echo -e "- starting OpenXPKI"
openxpkictl start                                                 >$LOG 2>&1

if [[ $(openxpkictl status 2>&1) != *"is running"* ]]; then
    echo -e "\nERROR: Could not start OpenXPKI. Please see logs in /var/log/openxpki"
    exit 333
fi
